import request from '@/utils/request'
import React from 'react'
import styles from './style.less'
import { Select, Input, Card, Tree, Switch, Button } from 'antd'

const { Option } = Select;
const { TreeNode } = Tree;


class ConfigViewer extends React.Component {

    state = {
        configJSON: {},
        switchChecked: true
    }

    componentDidMount() {
        request('config').then(res => {
            console.log(res)
            this.setState({ configJSON: res })

            const testCases = {...this.state.configJSON}
            delete testCases.Parameter
            delete testCases.Variant
            this.setState({ testCases })

    
            const checkedKeys = []
            this.getSelectedKeys('', testCases, checkedKeys)
            console.log('====checkedKeys', checkedKeys)
            this.setState({ checkedKeys })

            let expandedKeys = this.getExpandedKeysByChecked(checkedKeys)
            // expandedKeys = ["$$T01_FSI_COM_General$$TestCases$$T0101_Message_enumeration"]
            this.setState({ expandedKeys })
            console.log('====expandedKeys', expandedKeys)


 
        })
    }

    getSelectedKeys = (keyPrefix, dataObj, selectedKeys) => {
        Object.keys(dataObj).sort().map((k, idx) => {
            if (k === '') {
                return null
            }
            const currentKey = `${keyPrefix}$$${k}`
            if (typeof dataObj[k] === 'object') {
                this.getSelectedKeys(currentKey, dataObj[k], selectedKeys)
                return
            }
            if (dataObj[k]) {
                selectedKeys.push(currentKey)
            }
        });
    }

    getExpandedKeys = (keyPrefix, dataObj, expandedKeys) => {
        Object.keys(dataObj).sort().map((k, idx) => {
            if (k === '') {
                return null
            }
            const currentKey = `${keyPrefix}$$${k}`
            if (typeof dataObj[k] === 'object') {
                Object.keys(dataObj[k]).some(kk=>{
                    if(dataObj[k][kk]){

                    }
                })
                expandedKeys.push(currentKey)
                this.getExpandedKeys(currentKey, dataObj[k], expandedKeys)
                return
            }
        });
    }

    getExpandedKeysByChecked = (selectedKeys) =>{
        const s = new Set()
        selectedKeys && selectedKeys.forEach(k=>{
            const sk = k.split('$$')
            for(let i=0; i< sk.length - 1; i++){
                const tempk = sk.slice(0,i+1).join('$$')
                if(tempk){
                    s.add(tempk)
                }
            }

        })

        return Array.from(s)
    }

    renderTreeNodes = (keyPrefix, dataObj) => {
        if(!dataObj){
            return null
        }
        return Object.keys(dataObj).sort().map((k, idx) => {
            if (k === '') {
                return null
            }
            if (typeof dataObj[k] === 'object') {
                return (
                    <TreeNode title={k} key={`${keyPrefix}$$${k}`}>
                        {this.renderTreeNodes(`${keyPrefix}$$${k}`, dataObj[k])}
                    </TreeNode>
                );
            }
            return <TreeNode key={`${keyPrefix}$$${k}`} title={k} />;
        });
    }

    onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
    };

    onCheck = (checkedKeys, info) => {
        console.log('onCheck', checkedKeys, info);
        this.setState({ checkedKeys })
    };
    
    onExpand = (expandedKeys, info) => {
        console.log('onExpand', expandedKeys, info);
        this.setState({ expandedKeys })
    };

    // variant
    onVariantChange(value) {
        console.log(`selected ${value}`);
        const configJSON = {...this.state.configJSON}
        Object.keys(this.state.configJSON.Variant).forEach(k=>{
            configJSON.Variant[k] = k===value ? true : false
        })
        
        this.setState({
            configJSON
        })
    }

    // parameter
    onParamChange (pk, event) {
        console.log(`onParamChange `, pk, event, event.target.value)
        const configJSON = this.state.configJSON || {}
        configJSON.Parameter[pk] = event.target.value
        this.setState({configJSON})
    }

    submit (){
        console.log('configJSON====', this.state.configJSON)
        request('/saveConfig', {
            method: 'POST',
            data: this.state.configJSON
        })
    }

    render() {

        function onBlur() {
            console.log('blur');
        }

        function onFocus() {
            console.log('focus');
        }

        function onSearch(val) {
            console.log('search:', val);
        }




        if (!this.state.configJSON) {
            return <div>
                invalid config content
            </div>
        }
        const { Variant, Parameter } = this.state.configJSON
        if (!Variant) {
            return <div>
                invalid config content
            </div>
        }


        return <div style={{display: 'flex', flexDirection:'column', justifyContent: 'center',
        alignItems: 'center'}} >

            <Card title="Variant" style={{ width: 600, marginBottom: 10 }}>

                <Select
                    showSearch
                    style={{ width: '100%' }}
                    placeholder="Select a Variant"
                    onChange={this.onVariantChange.bind(this)}
                    onFocus={onFocus}
                    onBlur={onBlur}
                    onSearch={onSearch}
                    filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    defaultValue = {Object.keys(this.state.configJSON.Variant).filter(k=>this.state.configJSON.Variant[k])}
                >
                    {Object.keys(Variant).sort().map(k => {
                        return <Option value={k}>{k}</Option>
                    })}
                </Select>
            </Card>

            {/* <div>{JSON.stringify(Object.keys(Variant).sort())}</div> */}
            <Card title="Parameter" style={{ width: 600, marginBottom: 10 }}>

                {Object.keys(Parameter).sort().map(k => {
                    return <div><p style={{marginBottom:'0px', marginTop:'10px'}}>{k}</p>
                    <Input defaultValue={Parameter[k]} onChange={this.onParamChange.bind(this, k)}></Input></div>
                })}
            </Card>

            <Card title="Test Cases" style={{ width: 600, marginBottom: 10 }} extra={
                <Switch checkedChildren="Expanded" unCheckedChildren="Unexpanded"
                    checked={this.state.switchChecked} 
                    onChange={v=>{
                        let expandedKeys = []
                        if(v){
                            expandedKeys = this.getExpandedKeysByChecked(this.state.checkedKeys)
                        }
                        this.setState({switchChecked: v, expandedKeys})
                    }}/>
                }>
                <Tree
                    checkable
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    // defaultExpandAll = {true}
                    // autoExpandParent={true}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                // selectedKeys={this.state.selectedKeys}
                >
                    {this.renderTreeNodes('', this.state.testCases)}
                </Tree>
            </Card>

            <Button type="primary" onClick={this.submit.bind(this)}>Save</Button>
        </div>
    }
}
export default ConfigViewer